<template>
	<el-drawer
		v-model="showDialog"
		:size="dialogConfig?.width !== 'auto' ? dialogConfig?.width + 'px' : '50%'"
		title="I am the title"
		direction="rtl"
		append-to-body
		:close-on-click-modal="false"
		destroy-on-close
	>
		<template #header>
			<span class="title"
				><slot name="header"> {{ dialogConfig.title }}</slot></span
			>
		</template>
		<slot name="main">
			<LxDetail
				:config="dialogConfig.ExcuteData"
				:row="dialogConfig.formParmas!"
				v-if="dialogConfig.opType === 6 && dialogConfig.ExcuteData && dialogConfig.ExcuteData.isGroup === 1"
			/>
			<TableForm
				v-else-if="dialogConfig.opType !== 5"
				ref="tableFormRef"
				:fieldDefines="dialogConfig.fieldDefines"
				:OpType="dialogConfig.opType!"
				:inputData="props.inputData"
				:rowParams="dialogConfig.formParmas"
				:pageData="pageData"
			/>
			<!-- 自定义表单 -->
			<CustomTablePape
				v-else-if="dialogConfig.opType === 5 && dialogConfig.ot === 2"
				:inputData="{ ...props.inputData, ...dialogConfig.superiorParams, ...dialogConfig.formData }"
				:pageid="pageid"
				:tempPageData="{ ...dialogConfig.formData }"
				:isDisabledHanlde="dialogConfig.isDisabledHanlde || false"
				:isTabRadio="dialogConfig.isTabRadio || false"
				:fromPageID="dialogConfig.fromPageID"
				@dialogCloseRefreshEmit="handleDialogCloseRefreshEmit"
			/>
			<!-- 自定义页面 -->
			<template v-if="dialogConfig.opType === 5 && dialogConfig.ot === 3">
				<CustomPage
					:pageid="pageid"
					:dialog-data="dialogConfig.formData"
					:inputData="{ ...props.inputData, ...(dialogConfig.superiorParams?.queryParams || dialogConfig.superiorParams) }"
					@handleEmitEvent="handleEmitEvent"
					@clone="handlerDialogClose"
				></CustomPage>
			</template>
		</slot>
		<div v-if="dialogConfig.opType == 5 || dialogConfig.opType == 6" style="margin-bottom: 20px"></div>
		<template #footer v-if="dialogConfig?.opType !== 5 && dialogConfig?.opType !== 6">
			<slot name="footer"
				><div class="footer-btn">
					<el-button @click="handleCancel">取消</el-button> <el-button type="primary" @click="handleSubmit">确定</el-button>
				</div></slot
			>
		</template>
	</el-drawer>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { DialogConfigType, DialogType, TabFieldType } from '/@/components/Linxyun/custom/DataStructs/commontype';
import Lxy_params_mgr from '../custom/CustomCommon/lxy_params_mgr.js';
import Lxy_expression from '../custom/CustomCommon/lxy_expression.js';
import { httpReqeustApi } from '/@/api/linxyun/base';
import TableForm from '../custom/TableForm/index.vue';
import CustomTablePape from '../custom/CustomTablePape/index.vue';
import CustomPage from '../custom/CustomizePage/index.vue';
import LxDetail from './lx-detail.vue';
import { Base64 } from '/@/utils/b64';
import * as monaco from 'monaco-editor';

import { useCustomTableStore } from '/@/stores/customTable';
const customTableStore = useCustomTableStore();
customTableStore.setBatchAddData([]);
customTableStore.fromPageID = -1;
const props = withDefaults(
	defineProps<{
		modelValue?: boolean;
		dialogConfig: DialogConfigType;
		inputData?: Record<string, any>;
		pageData?: Record<string, any>;
	}>(),
	{ inputData: () => ({}), pageData: () => ({}) }
);
const { dialogConfig, inputData } = toRefs(props);
const emit = defineEmits(['update:modelValue', 'getTableData', 'exportExcel', 'handleEmitEvent']);

const httpRequest = httpReqeustApi();
const showDialog = ref(false);

// 为后代组件提供依赖
provide('dialogTablePage', true);

console.log('dialogConfig', props.dialogConfig);
provide('dialogConfig', props.dialogConfig || {});
watch(
	() => props.dialogConfig,
	(val) => {
		if (val.formData) {
			provide('tempPageData', val.formData || {});
			console.log('dialogConfig.value.formData', dialogConfig.value);
		}
	},
	{
		deep: true,
	}
);
watch(
	() => props.modelValue,
	(val) => {
		showDialog.value = val || false;
	}
);
watch(showDialog, (val) => {
	if (showDialog.value !== props.modelValue) {
		emit('update:modelValue', val);
	}
});

const tableFormRef = ref<InstanceType<typeof TableForm>>();

// pageid
const pageid = computed(() => {
	return Number(dialogConfig?.value?.submitUrl);
});

// 点击取消是调用
const handleCancel = () => {
	const values = Object.values(tableFormRef.value!.formData);
	const index = values.findIndex((val) => {
		return val !== '';
	});
	if (index === -1) {
		showDialog.value = false;
		return;
	}
	ElMessageBox.confirm('确定要关闭该表单？', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		showDialog.value = false;
	});
};

// 点击提交时处理
const handleSubmit = async () => {
	tableFormRef.value!._tableFormRef?.validate(async (valid, fields) => {
		const loading = ElLoading.service({
			lock: true,
			text: 'Loading',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		console.log('handleSubmit getModelMarkers', monaco.editor.getModelMarkers({}));
		if (monaco.editor.getModelMarkers({})?.length > 0) {
			loading.close();
			ElMessage.warning('编辑器代码异常，请检查代码规范');
			return;
		}
		if (valid) {
			if (!dialogConfig.value.submitUrl) {
				return ElMessage.error(`${dialogConfig.value.title}接口为空 submitUrl: ${dialogConfig.value.submitUrl}`);
			}
			await tableFormRef.value!.uploadFile();
			if (dialogConfig.value.opType === DialogType.add) {
				handleAddForm();
			} else if (dialogConfig.value.opType === DialogType.edit) {
				handleEditForm();
			} else if (dialogConfig.value.opType === DialogType.export) {
				emit('exportExcel', tableFormRef.value!.formData, dialogConfig.value.params || {});
				showDialog.value = false;
			}
		} else {
			console.warn(fields);
		}
		loading.close();
	});
};

// 添加
const handleAddForm = async () => {
	const formData = { ...tableFormRef.value?.formData } || {};
	const index = dialogConfig.value.fieldDefines.findIndex((item) => {
		return item.InputType === 'rich' && item.DataStorageMode === 'file';
	});
	// if (index !== -1) {
	// 	const field = dialogConfig.value.fieldDefines[index];
	// 	formData[field.FieldName] = formData[field.FieldName].match(/<p>(.*?)<\/p>/)[1];
	// }
	console.log('handleAddForm formData', formData);
	const params = form2Params(dialogConfig.value.fieldDefines, formData);
	console.log('handleAddForm params', params);
	try {
		const res: any = await httpRequest.Post(dialogConfig.value.submitUrl, {}, params);
		if (res.msg && res.msg === 'fail') {
			ElMessage({
				message: '添加失败',
				type: 'error',
				duration: 5 * 1000,
			});
		} else {
			ElMessage({
				message: '添加成功',
				type: 'success',
				duration: 5 * 1000,
			});
			emit('getTableData');
			showDialog.value = false;
			tableFormRef.value!.formData = {};
		}
	} catch (err) {
		console.error(err);
	}
};
// 修改
const handleEditForm = async () => {
	// 当前行的所有参数

	const tempFormParmas = dialogConfig.value.formParmas;
	const formData = { ...tableFormRef.value?.formData } || {};
	const index = dialogConfig.value.fieldDefines.findIndex((item) => {
		return item.InputType === 'rich' && item.DataStorageMode === 'file';
	});

	if (index !== -1) {
		const field = dialogConfig.value.fieldDefines[index];
		if (formData[field.FieldName] && formData[field.FieldName].match(/<p>(.*?)<\/p>/)) {
			formData[field.FieldName] = formData[field.FieldName] && formData[field.FieldName].match(/<p>(.*?)<\/p>/)[1];
		}
	}
	console.log('handleEditForm formData', formData);
	const params = form2Params(dialogConfig.value.fieldDefines, { ...tempFormParmas, ...formData });
	console.log({ ...tempFormParmas, ...formData }, params);
	try {
		console.log('submitUrl', dialogConfig.value.submitUrl);
		const res: any = await httpRequest.Post(dialogConfig.value.submitUrl, {}, params);
		if (res.msg && res.msg === 'fail') {
			ElMessage({
				message: '修改失败',
				type: 'error',
				duration: 5 * 1000,
			});
		} else {
			ElMessage({
				message: '修改成功',
				type: 'success',
				duration: 5 * 1000,
			});
			emit('getTableData');
			showDialog.value = false;
			tableFormRef.value!.formData = {};
		}
	} catch (err) {
		console.error(err);
	}
};

const form2Params = (fieldsDefine: TabFieldType[], formData: Record<string, any>) => {
	console.log('[Debug][form2Params], fields define: ', fieldsDefine, formData);
	const params: Record<string, any> = {};
	for (let i = 0; i < fieldsDefine.length; i++) {
		const field = fieldsDefine[i];
		// systime exp 非界面填值，可以先计算.
		if (field.InputType === 'systime') {
			params[field.FieldName] = '_SysTime_';
		} else if (field.InputType === 'exp') {
			if (field.InputDefine && field.InputDefine.Expression) {
				const datas = new Lxy_params_mgr(formData, props.inputData, null);
				const value = Lxy_expression.calPrefixExp(field.InputDefine.Expression, datas);
				if (value === undefined || value === null) {
					console.error('[Error][form2Params]Call exp value for exp field, field : ', fieldsDefine[i].FieldName);
				} else {
					params[field.FieldName] = value;
				}
			}
		}
		// 处理时间范围
		// else if (fieldsDefine[i].InputType === 'el-time' && fieldsDefine[i].InputDefine?.filterType === 'range') {
		// 	const val = formData[fieldsDefine[i].FieldName];
		// 	console.log('val', val);
		// 	if (val) {
		// 		params[fieldsDefine[i].InputDefine.start] = val[0];
		// 		params[fieldsDefine[i].InputDefine.end] = val[1];
		// 	} else {
		// 		params[fieldsDefine[i].InputDefine.start] = '';
		// 		params[fieldsDefine[i].InputDefine.end] = '';
		// 	}
		// }

		if (!formData.hasOwnProperty(fieldsDefine[i].FieldName)) {
			console.log('[Debug][form2Params]Form data no key: ', fieldsDefine[i].FieldName);
			continue;
		}
		// if (field.type === 'time') {
		// 	params[field.FieldName] = formatTime2DB(formData[field.FieldName])
		// } else if (field.type === 'date') {
		// 	params[field.FieldName] = formatDate2DB(formData[field.FieldName])
		if (field.InputType === 'el-cascader') {
			console.log('[Debug]cascader, key : ', field.FieldName);
			const arData = formData[field.FieldName];
			if (!arData) {
				continue;
			}
			// if (!Array.isArray(arData)) {
			// 	console.error('[Error]Form data not array for cascader, key : ', field.FieldName, arData);
			// 	continue;
			// }
			if (arData.length === 0) {
				console.log('[Debug]Form data is empty for cascader, key : ', field.FieldName);
				continue;
			}

			console.log('[Debug]Form data for cascader, data : ', arData, arData[arData.length - 1]);
			// params[field.FieldName] = arData[arData.length - 1];
			params[field.FieldName] = arData;
		} else if (field.InputType === 'code-editor') {
			params[field.FieldName] = Base64.encode(formData[field.FieldName]);
		} else {
			params[field.FieldName] = formData[field.FieldName];
		}
	}
	console.log('[Debug][form2Params], params: ', params);
	return params;
};

const handleEmitEvent = (name: string, ...args: any) => {
	console.log('handleEmitEventhandleEmitEvent', name, args);

	emit('handleEmitEvent', name, ...args);
};

const handlerDialogClose = () => {
	console.log('handlerDialogClose');
	showDialog.value = false;
};

const handleDialogCloseRefreshEmit = () => {
	console.log('handleDialogCloseRefreshEmit');
	handlerDialogClose();
	emit('getTableData');
};
</script>
<style lang="scss" scoped>
.title {
	font-size: 22px;
	color: var(--el-color-primary);
	padding-left: 10px;
}
.title::after {
	content: '';
	position: absolute;
	left: 10px;
	width: 5px;
	height: 30px;
	background-color: var(--el-color-primary);
}
:deep(.el-form-item__content) {
	display: block;
}
.footer-btn {
	margin-bottom: 20px;
	margin-right: 10px;
}
</style>
